package web;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import command.Command;

import human.User;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

import jdbc.ConnectionPoolHolder;
import jdbc.DataAccessObject;
import jdbc.UserDao;

public class ServletElective extends javax.servlet.http.HttpServlet {

	private static final Logger log = Logger.getLogger(ServletElective.class.getName());

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		BasicConfigurator.configure();

		log.info("init() complete");
	}

	@Override
	public void destroy() {
		super.destroy();
		try {
			ConnectionPoolHolder.getInstance().getConnectionPool().dispose();
		} catch (SQLException e) {
			log.error("can't dispose connectionPool", e);
		}
		log.info("destroy() complete");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		processRequest(req, resp);

	}

	private void processRequest(HttpServletRequest request, HttpServletResponse response) {

		String page = null;
		Command command = RequestBuilder.getInstance().getCommand(request);

		page = command.execute(request, response);
		if (page == null) {
			page = "error.jsp";
		}
		try {
			getServletContext().getRequestDispatcher(page).forward(request, response);
		} catch (ServletException e) {
			log.error("process request - ServletException", e);
		} catch (IOException e) {
			log.error("process request - IOException", e);
		} finally {
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		processRequest(req, resp);

	}

}